<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Discount extends CI_Controller {
	var $perpage = 20;

		public function __construct() {
		   parent::__construct();
		   if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin()) redirect('auth/login/'.str_replace("/", ".",$_SERVER['REQUEST_URI']));
		   $this->layout->setlayout('admin/layout');
		   $this->crumps->push('/admin/discount/', 'Скидки');
		   $this->users_rights_model->check_rights(strtolower(get_class()), $this->router->get_method());
	   }

	public function index($id = 0)	{
		$data['pages'] = $pages = $this->db->select()->from('catalog_discount')->order_by('discount_procent', 'asc')->get()->result_array();
		$form = new jQuickForm('simple');
		$form->setLabel("Добавление скидки");
		$gr = $form->insertGroup()->addClass('col col2');
		$input = $gr->insertInputText('discount_procent')->setLabel('Размер скидки в процентах')->setComment('Дробное десятичное число, без знака процента')->setExample('15.00');
		$input->addRule('callback', 'Не верный формат', array('callback' => 'valid_float'), HTML_QuickForm2_Rule::CLIENT);
		$input->addRule('callback', 'Не верный формат', array('callback' => 'valid_float'), HTML_QuickForm2_Rule::SERVER);
		$input->addRuleRequired();
		$input = $gr->insertInputText('discount_price')->setLabel('Необходимая сумма')->setComment('Дробное десятичное число')->setExample('5000.00');
		$input->addRule('callback', 'Не верный формат', array('callback' => 'valid_float'), HTML_QuickForm2_Rule::CLIENT);
		$input->addRule('callback', 'Не верный формат', array('callback' => 'valid_float'), HTML_QuickForm2_Rule::SERVER);
		$input->addRuleRequired();

		if ($_SERVER['REQUEST_METHOD'] == "POST" && $form->validate()) {
			$p_data = $this->input->post();
			$this->db->insert('catalog_discount', $p_data);
			$this->session->set_flashdata('msg', 'Успешно добавлено');
			redirect('admin/discount');
		}

		$form->insertInputSubmit("Добавить");

		$data['form'] = $form."";
		$data['js'] = jQuickForm::js()->getJsAll();

		$this->layout->view('admin/discount/index', $data);
	}
	public function delete($id = 0) {
		if ($id != 0) $data['page'] = $page = $this->db->select()->from('catalog_discount')->where('discount_id', $id)->get()->result_array();
		if ($id != 0 && sizeof($page) <= 0) redirect('admin/discount');
		$this->db->where('discount_id', $id)->delete('catalog_discount');
		$this->session->set_flashdata('msg', 'Успешно удалено');
		redirect('admin/discount');
	}
}